#include <REGX51.H>

unsigned char code a[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
unsigned char code b[] = {0xfe, 0xfd, 0xfb, 0xf7};

unsigned char sec,min;
unsigned char Set_Min = 10;
bit Permit_Flag;
sbit SET = P3^1;
sbit LED = P3^2;
sbit UP = P3^4;
sbit DOWN = P3^7;

#define SEGPORT P2
#define BITPORT P1

void delay(unsigned char mx)
{
	unsigned char t;
	while(mx--)
		for(t = 0; t < 124; t++);
}

void display()
{
	unsigned char u;
	unsigned char buffer[] = {0,0,0,0};
	if(Permit_Flag == 1)
	{
		buffer[3] = Set_Min/10;
		buffer[2] = Set_Min%10;
	}
	else
	{
		buffer[3] = min/10;
		buffer[2] = min%10;
	}
	buffer[1] = sec/10;
	buffer[0] = sec%10;
	for(u = 0; u < 4; u++)
	{
		if(Permit_Flag == 1 && (u == 0 || u == 1))
			SEGPORT = 0xbf;
		else
			SEGPORT = a[buffer[u]];
		
		BITPORT = b[u];
		delay(5);
		SEGPORT = 0xff;
	}
}

void main()
{
	unsigned char i,j,k;
	bit Set_Flag,Up_Flag,Down_Flag;
	bit Done_Flag;
	TMOD = 0x01;
	TH0 = (65536 - 50000/1)/256;
	TL0 = (65536 - 50000/1)%256;
	
	while(1)
	{
		SET = 1;
		if(SET == 0)
			delay(10);
		if(SET == 0)
			Set_Flag = 1;
		if(SET==1 && Set_Flag == 1)
		{
			++i;
			Set_Flag = 0;
		}
		if(i == 1)
		{
			TR0 = 0;
			Permit_Flag = 1;
			Done_Flag = 0;
		}
		if(i == 2)
		{
			i = 0;
			Permit_Flag = 1;
			TR0 = 1;
		}
		UP = 1;
		if(UP == 0)
			delay(10);
		if(UP == 0)
			Up_Flag	= 1;
		if(UP == 1 && Up_Flag == 1 && Permit_Flag == 1)
		{
			++Set_Min;
			Up_Flag = 0;
		}
		DOWN = 1;
		if(DOWN == 0) delay(10);
		if(DOWN == 0) Down_Flag = 1;
		if(DOWN == 1 && Down_Flag == 1 && Permit_Flag == 1)
		{
			if(Set_Min > 1)
				Set_Min--;
			Down_Flag = 0;
		}
		if(TF0 = 1)
		{
			TF0 = 0;
			TH0 = (65536 - 50000/1)/256;
			TL0 = (65536 - 50000/1)%256;
			if(++j == 12)
			{
				j = 0;
				if(++sec == 60)
				{
					sec = 0;
					if(++min == 99)
						min = 0;
				}
			}
		}
		
		if(Set_Min == min && sec == 0)
		{
			TR0 = 0;
			LED = 0;
			Set_Min = 10;
			min = 0;
			Done_Flag = 1;
		}
		if(LED == 0)
		{
			for(k = 0; k < 20; k++)
				delay(100);
			LED = 1;
		}
		if(Done_Flag == 0)
		{
			display();
		}
	}
}

